#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# Copyright 2013 suliu.net
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#codeby     道长且阻
#email      ydhcui@suliu.net/QQ664284092
#website    http://www.suliu.net
#

try:
  import urllib as parse
  import urllib2 as request
  import cookielib as cookiejar
except ImportError as e:
  #print(e)
  from urllib import parse,request
  from http import cookiejar

import os,sys,json
import re
import socket
import smtplib
from email.mime.text import MIMEText

class SendMail(object):
    '''发送txt文本邮件'''
    def __init__(self,username,password):
        self.mail_host   ="smtp.qq.com"      #设置服务器
        self.mail_from   ="qq.com"           #发件箱的后缀
        self.mail_user   =username           #用户名
        self.mail_pass   =password           #口令


    def send(self,to_list,sub,content):
        me  = "%s<%s@qq.com>"%('robot',self.mail_user)
        msg = MIMEText(content,_subtype='plain',_charset='gb2312')
        msg['Subject'] = sub
        msg['From'] = me
        msg['To'] = ";".join(self.mailto_list)
        try:
            server = smtplib.SMTP()
            server.connect(self.mail_host)
            server.login(self.mail_user,self.mail_pass)
            server.sendmail(me, to_list, msg.as_string())
            server.close()
            return True
        except Exception as e:
            print(str(e))
            return False

def getheaders(url,header={}):
    try:
        url=url.decode("utf8")
    except:
        url=url
    cookie = cookiejar.MozillaCookieJar(getres(url.replace('/','#').replace(':','@').replace('?','@')))
    cj = request.HTTPCookieProcessor(cookie)
    opener = request.build_opener(cj)
    req = request.Request(url=url,headers=header)
    fp = opener.open(req)
    cookie.save(ignore_discard=True,ignore_expires=True)
    header.update(fp.getheaders())
    header['Cookie']=';'.join(['%s=%s'%(x.name,x.value) for x in cookie])
    mybytes = fp.read()
    try:
        mystr = mybytes.decode("utf8")
    except:
        mystr = mybytes
    fp.close()
    header['Result']=mystr
    return header

def get(url,header={}):
    try:
        url=url.decode("utf8")
    except:
        url=url
    cookie = cookiejar.MozillaCookieJar()
    cj = request.HTTPCookieProcessor(cookie)
    opener = request.build_opener(cj)
    req = request.Request(url=url,headers=header)
    fp = opener.open(req)
    mybytes = fp.read()
    try:
        mystr = mybytes.decode("utf8")
    except:
        mystr = mybytes
    fp.close()
    return mystr

def post(url,data,headers={}):
    postdata = parse.urlencode(data)
    postdata = postdata.encode('utf-8')
    cookie = cookiejar.MozillaCookieJar()
    cj  =  request.HTTPCookieProcessor(cookie)
    opener = request.build_opener(cj)
    req = request.Request(url, data=postdata,headers=headers)
    fp = opener.open(req)
    mybytes = fp.read()
    try:
        res = mybytes.decode("utf8")
    except:
        res = mybytes
    fp.close()
    return res

def find(source, startStr, endStr):
    try:
        start = source.index(startStr)
        source= source[start + len(startStr):]
        end   = source.index(endStr)
        data  = source[:end]
        return data
    except:
        return None

def getpath(res):
    path=os.path.dirname(sys.argv[0])
    return os.sep.join([path,res])

def getres(res):
    return os.sep.join([getpath('res'),res])

def html2str(htmlstr):
    #去除html标签 获取纯文本(
    re_cdata=re.compile('//<!\[CDATA\[[^>]*//\]\]>',re.I) #匹配CDATA
    re_script=re.compile('<\s*script[^>]*>[^<]*<\s*/\s*script\s*>',re.I)#Script
    re_style=re.compile('<\s*style[^>]*>[^<]*<\s*/\s*style\s*>',re.I)#style
    re_br=re.compile('<br\s*?/?>')#处理换行
    re_h=re.compile('</?\w+[^>]*>')#HTML标签
    re_comment=re.compile('<!--[^>]*-->')#HTML注释
    s=re_cdata.sub('',htmlstr)#去掉CDATA
    s=re_script.sub('',s) #去掉SCRIPT
    s=re_style.sub('',s)#去掉style
    s=re_br.sub('\n',s)#将br转换为换行
    s=re_h.sub('',s) #去掉HTML 标签
    s=re_comment.sub('',s)#去掉HTML注释
    #去掉多余的空行
    blank_line=re.compile('\n+')
    s=blank_line.sub('\n',s)
    return s

def bddwz(url):
    res = post("http://dwz.cn/create.php",{'url':url})
    try:
      result = json.loads(res)['tinyurl']
    except:
      result = url
    return result

if __name__=='__main__':
    print(dwzcn('')
    )